package svgedit.gui.commands;

import svgedit.gui.Frame;
import svgedit.svg.SVGDocument;
import svgedit.svg.SVGElement;
import svgedit.svg.SVGGroup;

/**
 * Handles the undo and redo for grouping elements to the document
 * 
 * @author SARJ
 * 
 */
public class GroupCommand implements Command
{
	private SVGElement[] elements;
	private SVGDocument document;
	private SVGGroup group;

	/**
	 * Constructs the grouping command
	 * @param document The document that the group resides
	 * @param group The group reference that will be used
	 * @param elements The elements to group
	 */
	public GroupCommand(SVGDocument document, SVGGroup group,
			SVGElement[] elements)
	{
		this.document = document;
		this.group = group;
		this.elements = elements;
	}

	@Override
	public void executeUndo()
	{
		// Loop through each child
		SVGElement[] children = ((SVGGroup) group).getChildren();
		for (SVGElement child : children)
		{
			child.getParent().removeChild(child);
			document.getRootGroup().appendChild(child);
		}

		// Remove group
		group.getParent().removeChild(group);

		// Set selection
		Frame.getInstance().getView().setSelectedElements(children);

	}

	@Override
	public void executeRedo()
	{
		// Re group all children
		for (SVGElement elem : elements)
		{
			elem.getParent().removeChild(elem);
			group.appendChild(elem);
		}

		document.getRootGroup().appendChild(group);

		// Set selection
		Frame.getInstance().getView().setSelectedElement(group);

	}

}
